package cn.com.do1.component.merchant.merchantpay.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.exception.IllegalParameterException;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.component.merchant.merchant.service.IMerchantService;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantListVO;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantVO;
import cn.com.do1.component.merchant.merchantpay.model.*;
import cn.com.do1.component.merchant.merchantpay.service.IMerchantpayService;
import cn.com.do1.component.merchant.merchantpay.vo.TbCzMerchantPayVO;
import cn.com.do1.component.systemmgr.user.model.User;
import cn.com.do1.component.util.ExcelUtil;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import cn.com.do1.common.util.AssertUtil;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.common.util.security.SecurityUtil;
import cn.com.do1.dqdp.core.DqdpAppContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司 All rights reserved. User: ${user}
 */
public class MerchantpayAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(MerchantpayAction.class);
    private IMerchantpayService merchantpayService;
    private TbCzMerchantPayPO tbCzMerchantPayPO;
    private String ids[];
    private String id;
    private String personId;
    private String userId;
    private String newPassword;

    @Resource
    private IMerchantService merchantService;

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public IMerchantpayService getMerchantpayService() {
        return merchantpayService;
    }

    @Resource
    public void setMerchantpayService(IMerchantpayService merchantpayService) {
        this.merchantpayService = merchantpayService;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {@SearchValueType(name = "userName", type = "string",
            format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("merchantpayList")
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = merchantpayService.searchMerchantpay(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {@SearchValueType(name = "userName", type = "string",
            format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("merchantpayMyList")
    public void ajaxMySearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        getSearchValue().put("personId", this.personId);
        pager = merchantpayService.searchMyMerchantpay(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }


    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        // todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        // todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        // 完成批量更新的代码
    }

    public void setTbCzMerchantPayPO(TbCzMerchantPayPO tbCzMerchantPayPO) {
        this.tbCzMerchantPayPO = tbCzMerchantPayPO;
    }

    public TbCzMerchantPayPO setTbCzMerchantPayPO() {
        return this.tbCzMerchantPayPO;
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "充值成功", faileMsg = "充值失败"))
    public void addTbCzMerchantPayPO() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();

            TbCzMerchantVO vo = this.merchantService.getMerchantByPersonId(user.getPersonId());
            if (SecurityUtil.getMd5Code(newPassword).equals(vo.getPayPassword())) {
                tbCzMerchantPayPO.setTbMerchatPayOper(user.getUsername());
                tbCzMerchantPayPO.setTbMerchatPayInsert(new Date());
                if (AssertUtil.isEmpty(tbCzMerchantPayPO.getTbMerchatPayUserid())) {
                    if (AssertUtil.isEmpty(this.userId)) {
                        setActionResult("1002", "代理商充值参数出错");
                        logger.error("代理商充值参数出错");
                    } else {
                        tbCzMerchantPayPO.setTbMerchatPayUserid(userId);
                        this.merchantpayService.addMerchantpay(tbCzMerchantPayPO);
                    }
                } else {
                    this.merchantpayService.addMerchantpay(tbCzMerchantPayPO);
                }
            } else {
                setActionResult("1002", "充值支付密码不正确，充值失败");
            }


        } catch (Exception e) {
            setActionResult("1002", "充值参数错误，充值失败");
            logger.error(e.getMessage(), e);
        } catch (BaseException e) {
            setActionResult("1002", "充值参数错误，充值失败");
            logger.error(e.getMessage(), e);
        }

    }

    public void updateTbCzMerchantPayPO() {
        super.ajaxUpdate(tbCzMerchantPayPO);
    }

    public void deleteTbCzMerchantPayPO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbCzMerchantPayPO._setPKValue(id);
        super.ajaxDelete(tbCzMerchantPayPO);
    }

    @ActionRoles("merchantpayDelete")
    public void batchDeleteTbCzMerchantPayPO() {
        super.ajaxBatchDelete(TbCzMerchantPayPO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxView() throws Exception, BaseException {
        TbCzMerchantPayPO xxPO = merchantpayService.searchByPk(TbCzMerchantPayPO.class, id);
        addJsonFormateObj("tbCzMerchantPayPO", xxPO);// 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    public TbCzMerchantPayPO getTbCzMerchantPayPO() {
        return this.tbCzMerchantPayPO;
    }

    @SearchValueTypes(nameFormat = "false", value = {@SearchValueType(name = "userName", type = "string",
            format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("merchantpayExport")
    public String export() {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);
        List<TbCzMerchantPayVO> list = null;
        try {
            pager = this.merchantpayService.searchMerchantpay(getSearchValue(), pager);
            list = (List<TbCzMerchantPayVO>) pager.getPageData();

        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
        } finally {
        }

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head = {"平台充值订单号", "充值账户名称", "充值金额", "充值状态", "充值时间", "操作人"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbCzMerchantPayVO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "商户平台充值信息" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }
}
